'use client';

import type { TMetadata } from '@/types';
import { useQuery } from '@tanstack/react-query';
import { clientQueryAllMenu } from '@/services/api';
import type { IMenu } from '@/interfaces';
import NavbarAdminPage from '@/app/[locale]/admin/navbar';
import { NavbarPage } from '@/app/[locale]/navbar';
import FooterPage from '@/app/[locale]/footer';
import AlertLoad from '@/app/[locale]/alert/load';
import Alert from '@/app/[locale]/alert/alert';
import { useTranslations } from 'use-intl';

export default function HomeAdminPage({ metadata }: { metadata: TMetadata }) {
  return (
    <>
      <NavbarPage metadata={metadata} />
      <HomeAdmin metadata={metadata} />
      <FooterPage metadata={metadata} />
    </>
  );
}

const HomeAdmin = ({ metadata }: { metadata: TMetadata }) => {
  const t = useTranslations('AdminPage');

  const clientQueryMenusQuery = useQuery(
    metadata.all['menus'].k,
    async (context) => {
      return (await clientQueryAllMenu()) as IMenu[];
    },
    {
      initialData: metadata.all['menus'].v as IMenu[],
    },
  );

  if (clientQueryMenusQuery.data) {
    const menus = clientQueryMenusQuery.data;

    return (
      <div className="container-fluid">
        <NavbarAdminPage menus={menus} />

        <div className="row">
          <div className="col">
            {menus.length > 0 ? (
              <div className="vh-100 d-flex align-items-center justify-content-center">
                <i className="bi bi-emoji-wink fs-1 me-2 d-flex"></i>
                <div className="fs-2">{metadata.env.APP_NAME}</div>
              </div>
            ) : (
              <div className="text-center text-secondary">
                {t('noMenuAvailable')}
              </div>
            )}
          </div>
        </div>
      </div>
    );
  }

  if (clientQueryMenusQuery.error) {
    return <Alert message={clientQueryMenusQuery.error} />;
  }

  return <AlertLoad />;
};
